package com.tbl.modules.wms.controller.baseinfo;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.FactoryArea;
import com.tbl.modules.wms.entity.baseinfo.Workshop;
import com.tbl.modules.wms.service.baseinfo.FactoryAreaService;
import com.tbl.modules.wms.service.baseinfo.WorkshopService;
import com.tbl.modules.wms.service.webservice.client.WmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 车间管理控制层
 * @author 70486
 */
@Controller
@RequestMapping(value = "/workshop")
public class WorkshopController extends AbstractController {

    /**
     * 车间
     */
    @Autowired
    private WorkshopService workshopService;
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;
    /**
     * 厂区信息
     */
    @Autowired
    private FactoryAreaService factoryAreaService;
    /**
     * wms调用入口
     */
    @Autowired
    private WmsService wmsService;

    /**
     * 跳转到车间管理列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.workshop));
        mv.setViewName("techbloom/baseinfo/workshop/workshop_list");
        return mv;
    }

    /**
     * 获取车间列表数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = workshopService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 生效
     * @param ids 车间主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/useful.do")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> useful(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        Workshop workshopEntity = new Workshop();
        workshopEntity.setState(Constant.LONG_ONE);
        boolean result = workshopService.update(workshopEntity, new EntityWrapper<Workshop>().in("ID", Arrays.asList(ids.split(","))));
        map.put("result", result);
        map.put("msg", result?"更新成功！":"更新失败！");
        return map;
    }

    /**
     * 失效
     * @param ids 车间主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/useless.do")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> useless(String ids) {
    	Map<String, Object> map = new HashMap<>(2);
        Workshop workshopEntity = new Workshop();
        workshopEntity.setState(Constant.LONG_ZERO);
        boolean result = workshopService.update(workshopEntity, new EntityWrapper<Workshop>().in("ID", Arrays.asList(ids.split(","))));
        map.put("result", result);
        map.put("msg", result?"更新成功！":"更新失败！");
        return map;
    }

    /**
     * 弹出到车间编辑/添加页面
     * @param id 车间主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd(Long id) {
        ModelAndView mv = this.getModelAndView();
        Workshop workshop;
        mv.setViewName("techbloom/baseinfo/workshop/workshop_edit");
        if(id==null) {
        	workshop = new Workshop();
        }else {
        	workshop = workshopService.selectById(id);
        	FactoryArea factoryArea = factoryAreaService.selectOne(new EntityWrapper<FactoryArea>().eq("CODE", workshop.getOrg()));
        	workshop.setFactoryCodeName(factoryArea.getCode()+"_"+factoryArea.getName());
        }
        mv.addObject("edit", id != null && id != Constant.LONG_ZERO ? Constant.INT_ONE : Constant.INT_ZERO);
        mv.addObject("workshop", workshop);
        return mv;
    }

    /**
     * 保存车间信息
     * @param workshop 车间
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveworkshop")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> saveworkshop(Workshop workshop) {
        System.out.println(">>>>>"+workshop);
        Map<String, Object> map = new HashMap<>(2);
        workshop.setState(Constant.LONG_ONE);
        boolean result = workshopService.insertOrUpdate(workshop);
        map.put("result", result);
        map.put("msg",result?"保存成功！":"保存失败！");
        return map;
    }

    /**
     * 导出Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            String sheetName = "车间" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            mapFields.put("name", "行车名称");
            mapFields.put("code", "行车编码");
            mapFields.put("factoryCode", "厂区编码");
            mapFields.put("factoryName", "厂区名称");
            mapFields.put("warehouseName", "所属仓库");
            DeriveExcel.exportExcel(sheetName, workshopService.getExcelList(request.getParameter("ids"), request.getParameter("queryCode"),
            request.getParameter("queryOrg"), null), mapFields, response, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步车间基础数据
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/synchronousdata.do")
    @ResponseBody
    public Map<String,Object> synchronousdata() {
    	try {
			Map<String, Object> xmlMap;
			logger.info(DateUtils.getTime() +" >>同步车间数据....");
	        xmlMap = new HashMap<>(1);
	        xmlMap.put("line", new HashMap<String, Object>(3) {{
	            put("orgid", "");
	            put("workshopnumber", "");
	            put("workshopname", "");
	        }});
	        wmsService.FEWMS026(xmlMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return new HashMap<String,Object>(2) {{
            put("result", true);
            put("msg", "更新成功！");
        }};
    }

}
